import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios/dist/axios'
import qs from 'qs'
import moment from 'moment'
Vue.use(Vuex)
axios.defaults.headers.post['Content-type']='application/json;charset=UTF-8';

export default new Vuex.Store({
  state: {
      selectTableId:{},
      mealContents: [],
      entryOrders :[],
      entryFoods :[],
      foodCount :[],
      seekTab: 0,
      focusTrIndex: -1,
      mealFocusTrIndex: -1,
      changeNum: 0,
      totalPrice: 0,
      Authorization: localStorage.getItem('Authorization') ? localStorage.getItem('Authorization') : '',
      user:sessionStorage.getItem('user')?JSON.parse(sessionStorage.getItem('user')):[],
      // rankList:sessionStorage.getItem('rankList')?JSON.parse(sessionStorage.getItem('rankList')):[]
  },
  getters: {
      mealContents: state => {
          if (state.mealContents == [] && sessionStorage.getItem("state.mealContents")){
              state.mealContents = sessionStorage.getItem("state.mealContents")
          }
          return state.mealContents;
      },
      totalPrice:state => {
          if (state.mealContents != []){
              state.totalPrice = 0;
              state.mealContents.forEach((food)=>{
                  state.totalPrice += food.price * food.count;
              })
          }else{
              state.totalPrice = 0
          }
          return parseInt(state.totalPrice);
      },
      changeNum(state){
          if(state.mealFocusTrIndex >= 0){
              // state.changeNum = state.mealContents[state.mealFocusTrIndex].count;
              Vue.set(state,"changeNum",state.mealContents[state.mealFocusTrIndex].count)
          }
          return state.changeNum;
      }
  },
  mutations: {
      flushFoods(state){
          axios.get("/api/food/list").then(req=>{
              Vue.set(state,"foodCount",[])
              // console.log(req.data);
              req.data.forEach((food)=>{
                  Vue.set(state.foodCount,state.foodCount.length,food)
              })
          })
      },
      flushEntry(state){
          axios.get('/api/entry/list').then(req => {
              Vue.set(state,"entryOrders",[])
              req.data.forEach( entry => Vue.set(state.entryOrders,state.entryOrders.length,entry))
          })
      },
      changeLogin (state, token) {
        this.state.Authorization = token;
        localStorage.setItem('Authorization', token);
      },
      addMeals(state,foodId){
          console.log(foodId)
          state.foodCount.forEach(food => {
              if(food.id === foodId){
                  let isAdd = true;
                  let idx = 0
                  for(let curr of state.mealContents){
                  // state.mealContents.forEach(curr =>{
                      if(curr.id === foodId){
                          curr.count++;//先改变数量，
                          Vue.set(state.mealContents,idx,food);//调用set,做响应式操作(添加属性的对象必须是state的成员变量)
                          isAdd = false;
                          break;
                      }
                  idx++;
                  }
                  // state.mealContents.forEach(contentFood => {
                  //     console.log("count",foodId)
                  //     if(contentFood.id == foodId){
                  //         // contentFood.count++;
                  //         Vue.set(contentFood,"count",contentFood.count+1);
                  //         isAdd = false;
                  //         console.log("add count")
                  //     }
                  // });
                  if(isAdd){
                      food.count = 1;
                      Vue.set(state.mealContents,state.mealContents.length,food);
                  }
              }
          });
          sessionStorage.setItem("state.mealContents",state.mealContents)
      },
      minusCount(state,index){
          // let idx = 0
          // for(let curr of state.mealContents){
          //     if(curr.id === foodId){
          //         if(curr.count === 1){//添加属性的对象必须是state的成员变量
          //             Vue.delete(state.mealContents,idx);
          //         }else{
          //             curr.count--;
          //         }
          //         break;
          //     }
          //     idx++
          // }
          if (state.mealContents[index].count === 1){
              Vue.delete(state.mealContents,index);
          }else{
              state.mealContents[index].count--
              Vue.set(state.mealContents,index,state.mealContents[index]);
          }
          sessionStorage.setItem("state.mealContents",state.mealContents)
      },
      plusCount(state,index){
          // for(let curr of state.mealContents){
          //     if(curr.id === foodId){
          //         curr.count++;
          //         break;
          //     }
          // }
          state.mealContents[index].count++
          Vue.set(state.mealContents,index,state.mealContents[index]);
          sessionStorage.setItem("state.mealContents",state.mealContents)
      },
      clearMeals(state){
          Vue.set(state,"mealContents",[])
          sessionStorage.setItem("state.mealContents",state.mealContents);
      },
      //提单
      billOrder(state){
          console.log(state.entryOrders[state.focusTrIndex])
          if(state.focusTrIndex !== -1 && state.seekTab === 1) {
              axios.get("/api/entry/bill/" + state.entryOrders[state.focusTrIndex].id).then(req => {
                  Vue.delete(state.entryOrders,state.focusTrIndex)
                  Vue.set(state,"mealContents",[]);
                  console.log(req.data)
                  req.data.entryFoods.forEach(entryFood => {
                      entryFood.food.count = entryFood.count;
                      Vue.set(state.mealContents,state.mealContents.length,entryFood.food);
                  })
              })
          }
      },
      //挂单
      entryOrder(state,remark) {
          let obligation= parseInt(state.totalPrice);
          let entryFoods= [];
          state.mealContents.forEach(meal => {
              let entryFood = {
                  foodId: meal.id,
                  count: meal.count
              }
              entryFoods.push(entryFood);
          });
          axios.post('/api/entry/add',{
              'obligation': obligation,
              'remark': remark,
              'entryFoods': entryFoods
          }).then(req => {
              console.log(req.data)
          }).catch(error =>{
              console.log(error)
          })
      },
      //删除
      removeEl(state){
          if(state.mealFocusTrIndex !== -1 && state.seekTab === 0){
              console.log('meal',state.mealFocusTrIndex)
              Vue.delete(state.mealContents,state.mealFocusTrIndex)
              // axios.
          };
          if(state.focusTrIndex !== -1 && state.seekTab === 1){
              console.log('entry',state.entryOrders[state.focusTrIndex].id);
              axios.get('/api/entry/del?id='+ state.entryOrders[state.focusTrIndex].id).then( response => {
                  Vue.delete(state.entryOrders,state.focusTrIndex);
              })
          }
      },
      //改变数量
      changeNum(state,num){
          state.mealContents[state.mealFocusTrIndex].count = num;
          Vue.set(state.mealContents,state.mealFocusTrIndex,state.mealContents[state.mealFocusTrIndex])
      }
  },
  actions: {

  },
  modules: {
  }
})
